package com.huaxin.hxcloud.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.huaxin.common.BaseApp;
import com.huaxin.common.BaseConfig;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.UserDTO;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.PrefUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ModifyPasswordActivity;
import com.huaxin.hxcloud.activity.RegisterActivity;
import com.huaxin.hxcloud.control.HxControlUtils;
import com.huaxin.hxcloud.service.LocationService;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.db.LocalAnnoStore;
import com.huaxindata.im.model.db.LocalWarnStore;
import com.huaxindata.im.model.db.MessageStore;

import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator  on 2016/9/6.
 */
public class LoginActivity extends AppCompatActivity {
    private static final boolean TEST = false;

    private static final String TAG = "LoginActivity";
    @BindView(R.id.logo)
    ImageView         logo;
    @BindView(R.id.et_username)
    TextInputEditText etUsername;
    @BindView(R.id.et_password)
    TextInputEditText etPassword;
    @BindView(R.id.bt_login)
    Button            btLogin;
    @BindView(R.id.login)
    LinearLayout      login;
    //    @BindView(R.id.cb_save_pw)
    //    CheckBox cbSavePw;
    @BindView(R.id.bt_register)
    Button            btRegister;
    @BindView(R.id.et_ip)
    TextInputEditText et_ip;
    @BindView(R.id.et_port)
    TextInputEditText et_port;
    @BindView(R.id.ipconfig_lv)
    LinearLayout      mInConfigLv;
    private ProgressDialog dialog;

    //定义是否自动登录的变量
    private boolean isAutoLogin;
    //定义变量确定是否第一次自动登录
    private boolean isFirstAutoLogin = true;

    private String[] infos = PrefUtil.loadLoginInfo();
    private int mSecureCode;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSecureCode = getIntent().getIntExtra("secure", 0);
        if (mSecureCode == 110) {//如果是由于登录异常才跳转到此界面则处理逻辑不一样
            initView();
            Log.e(TAG, "xxxx====异常登录,需要重新登录");
            return;
        }
        isAutoLogin = PrefUtil.get(Constants.PK_AUTO_LOGIN, false);
        //如果设置了自动登录，并且不是登出，则直接调用login函数
        dialog = DialogUtil.getWaitDialog(LoginActivity.this, "登录中");
        if (isAutoLogin) {
            login(infos[0], infos[1]);
        } else {
            initView();
        }
    }

    //初始化登录界面
    private void initView() {
        setContentView(R.layout.hx_activity_login);
        ButterKnife.bind(this);
        if (PrefUtil.get(Constants.PK_SAVE_PW, false)) {
            etUsername.setText(infos[0]);
            etPassword.setText(infos[1]);
        }
        if (HxControlUtils.isBUILDTYPES()) {
            mInConfigLv.setVisibility(View.VISIBLE);
        } else {
            mInConfigLv.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isFirstAutoLogin = false;//已经不是第一次自动登录了
        initView();
        ToastUtil.showToast(intent.getStringExtra("hint"));
    }

    public void login(final String userName, final String password) {
        if (TextUtils.isEmpty(userName)) {
            ToastUtil.showToast("请输入正确用户名");
            return;
        }
        if (password.equals("") || password.length() < 6) {
            ToastUtil.showToast("请输入正确密码");
            return;
        }
        if (dialog != null) {
            dialog.show();
        }
        if (!isAutoLogin) {
            String ipInput = et_ip.getText().toString().trim();
            String etPort = et_port.getText().toString().trim();
            if (!TextUtils.isEmpty(ipInput) && !etPort.isEmpty()) {
                //测试ip切换
                if (!ipInput.contains("http")) {
                    BaseConfig.setAddr("http://" + ipInput);
                } else {
                    BaseConfig.setAddr(ipInput);
                }
                BaseConfig.setPort(etPort);
                BaseConfig.setUrl(BaseConfig.getAddr() + ":" + BaseConfig.getPort());
                Log.e("lwjing", "baseUrl=" + BaseConfig.getUrl());
                RequestHelper.clearCookie();
                RequestHelper.clearRetrofit();
                RequestHelper.init(this);
            }
        }

        Call<UserDTO> call = RequestHelper.getRequestApi().login(userName, password);//hxadmin",
        // "hx@5236
        Log.d(TAG, "onResponse:login --->" + call.request().url());

        call.enqueue(new Callback<UserDTO>() {
            @Override
            public void onResponse(Call<UserDTO> call, Response<UserDTO> response) {
                final UserDTO user = response.body();
                if (response.isSuccessful() && user != null) {
                    if (user.isSuccessful()) {
                        if (mSecureCode == 110) {//如果是异常登录之后客户又登录成功了，只需关闭当前activity即可
                            finish();
                            return;
                        }
                        Global.setUser(user);
                        Global.getUser().setFirstOrgCode(user.getOrgCode());
                        UserManager.setHostUser(user);//向Chat模块注入UserDto对象

                        if (!TextUtils.isEmpty(Global.user.getServerAddress())) {
                            requsetBusinessLogint(Global.user.getServerAddress(), userName, password, dialog);
                        } else {
                            //  ToastUtil.showToastShort("数据异常");
                            //  dialog.dismiss();
                            intentToHome(userName, password, dialog, user.getUserId() + "");
                        }


                    } else {
                        ToastUtil.showToastShort(user.getMsg());
                        PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        if (isAutoLogin && isFirstAutoLogin) {
                            reLogin(user.getMsg());
                            // return;
                        }
                    }
                } else {
                    ToastUtil.showToastShort("数据异常");
                    PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (isAutoLogin && isFirstAutoLogin) {
                        reLogin("数据异常");
                        // return;
                    }
                }
            }

            @Override
            public void onFailure(Call<UserDTO> call, Throwable t) {
                //16:02:07
                Log.d("----->", "onFailure: " + t);
                //如果是第一次自动登录失败，则重新启动loginActivity
                ToastUtil.showToastShort("网络故障");
                PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (isAutoLogin && isFirstAutoLogin) {
                    reLogin("网络故障");
                    // return;
                }
            }
        });
    }


    /**
     * 登录业务平台
     *
     * @param serverAddress
     * @param userName
     * @param password
     * @param dialog
     */
    private void requsetBusinessLogint(String serverAddress, final String userName, final String password, final ProgressDialog dialog) {
        HxTransmitRequestHelper.init(this, serverAddress);
        Call<UserDTO> transpondCall = HxTransmitRequestHelper.getRequestApi().login(userName, password);
        android.util.Log.d("lwjing ", "onResponse: --->" + transpondCall.request().url());
        transpondCall.enqueue(new Callback<UserDTO>() {
            @Override
            public void onResponse(Call<UserDTO> call, Response<UserDTO> response) {
                final UserDTO user = response.body();
                if (response.isSuccessful() && user != null) {
                    UserDTO userDto = Global.getUser();
                    userDto.setUserInfo(user.getUserInfo());
                    userDto.setWorkModuleArr(user.getWorkModuleArr());

                    userDto.setOrgCode(user.getOrgCode());
                    if (userDto.getOrgName() != null && !userDto.getOrgName().isEmpty()) {
                        userDto.setOrgName(user.getOrgName());
                    }

                    Log.e("lwjing", "PlatformName:" + UserManager.getPlatformName() + " orgname：" + UserManager.getOrgName());

                    intentToHome(userName, password, dialog, userDto.getUserId() + "");
                } else {
                    //接口请求 出现502 404
                    ToastUtil.showToastShort("数据异常");
                    PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    if (isAutoLogin && isFirstAutoLogin) {
                        reLogin("数据异常");
                        // return;
                    }
                }
            }

            @Override
            public void onFailure(Call<UserDTO> call, Throwable t) {
                //不是自动登录时关闭对话框
                ToastUtil.showToastShort("网络故障");
                PrefUtil.set(Constants.PK_AUTO_LOGIN, false);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 成功跳转首页
     *
     * @param userName
     * @param password
     * @param dialog
     */
    private void intentToHome(String userName, String password, ProgressDialog dialog, String userid) {
        if (dialog != null) {
            dialog.dismiss();
        }
        startService(new Intent(LoginActivity.this, LocationService.class));
        //登录的时候将用户名和密码都保存起来，无论用户有无设置保存密码
        savePassword(userName, password);
        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
        PrefUtil.set(Constants.PK_AUTO_LOGIN, true);
        setJpushAlias(userid);
        finishActivity();
    }

    /**
     * 设置极光推送(别名ID)
     *
     * @param userind
     */
    private void setJpushAlias(String userind) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, "account_" + userind));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "jpush Set tag and alias success alias=" + alias + " tags=" + tags;
                    Log.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "jpush Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "jpush Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
        }
    };

    private static final int     MSG_SET_ALIAS = 1001;
    @SuppressLint("HandlerLeak")
    private final        Handler mHandler      = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler." + msg.obj);
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj, null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    //自动登录失败后，重新显示登录界面,hint为自动登录失败原因
    private void reLogin(String hint) {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.putExtra("hinthint", hint);
        startActivity(intent);
    }

    private void savePassword(String userName, String password) {
        PrefUtil.saveLoginInfo(userName, password);
    }


    @OnClick({R.id.bt_login, R.id.bt_register, R.id.bt_modify})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_login:

                String userName = etUsername.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                // sadvePassword(userName, passwor);

                login(userName, password);
                break;
            case R.id.bt_register: //注册
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.bt_modify://忘记密码
                startActivity(new Intent(this, ModifyPasswordActivity.class));
                break;
        }
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    private void finishActivity() {
        initMessageStore();
        //        startService(new Intent(this, MessageService.class));
        finish();
    }

    /**
     * 初始化消息接收的数据库对象
     */
    private void initMessageStore() {
        MessageStore.init(LoginActivity.this);
        LocalAnnoStore.getAnnoStore(LoginActivity.this);
        LocalWarnStore.getWarnStore(LoginActivity.this);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //如果是安全登录异常的话，客户登录不成功,并且按了返回，则要关闭栈中所有的activity
        if (mSecureCode == 110) {
            List<Activity> createdActivities = BaseApp.getCreatedActivities();
            for (Activity activity : createdActivities) {
                activity.finish();
            }
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}
